package models

import (
	"social-app/dao"
	"time"
)

type UserProfile struct {
	Id         int       `json:"id"`
	UserId     int       `json:"user_id"`
	Avatar     string    `json:"avatar"`
	Intro      string    `json:"intro"`
	Sex        int       `json:"sex"`
	WechatCode string    `json:"wechat_code"`
	RegIp      string    `json:"reg_ip"`
	Address    string    `json:"address"`
	Birthday   time.Time `json:"birthday"`
}

func (u *UserProfile) TableName() string {
	return "user_profile"
}

func CreateUserProfile(userId int, regIp string) error {
	userProfile := &UserProfile{
		UserId: userId,
		RegIp:  regIp,
	}
	return dao.Db.Create(&userProfile).Error
}

func GetUserProfileByUserId(userId int) (*UserProfile, error) {
	userProfile := &UserProfile{}
	err := dao.Db.Where("user_id=?", userId).First(&userProfile).Error
	return userProfile, err
}

func UpdateUserProfileByUserId(userId int, avatar string, intro string, sex int, wechatCode string, address string, birthday string) error {
	userProfile, _ := GetUserProfileByUserId(userId)
	if avatar != "" {
		userProfile.Avatar = avatar
	}
	if intro != "" {
		userProfile.Intro = intro
	}
	if sex != 0 {
		userProfile.Sex = sex
	}
	if wechatCode != "" {
		userProfile.WechatCode = wechatCode
	}
	if address != "" {
		userProfile.Address = address
	}
	if birthday != "" {
		// 获取本地时区
		loc, err := time.LoadLocation("Local")
		if err != nil {
			panic("加载时区时出错")
		}

		t, err := time.ParseInLocation("2006-01-02 15:04:05", birthday, loc)
		if err != nil {
			panic("时间格式错误")
		}
		userProfile.Birthday = t
	}
	return dao.Db.Where("user_id = ?", userId).Save(&userProfile).Error
}
